<script setup lang='ts'>
import { onLoad } from '@dcloudio/uni-app'
import { queryWxPayStatusAPI, wxPayAPI } from '@/services/pay'
import { ref } from 'vue'
import type { PayDto } from '@/types/pay'

const query = defineProps<{
  selectedItems: string
  chId: string
}>()

// 二维码弹出层的开启
const urCode = ref<PayDto>()
const parsedSelectedItems = ref<any[]>([]) // 根据实际数据类型定义
let timer: ReturnType<typeof setInterval> | null = null

onLoad(async () => {
  console.log(query.chId)
  parsedSelectedItems.value = JSON.parse(query.selectedItems)
  console.log('itemId', parsedSelectedItems.value)
  const res = await wxPayAPI(parsedSelectedItems.value)
  urCode.value = res.data

  // 启动定时器查询支付状态
  timer = setInterval(async () => {
    const res = await queryWxPayStatusAPI(urCode.value?.orderNo)
    if (res.code === 200) {
      // 支付成功，清除定时器
      if (timer) {
        clearInterval(timer)
        timer = null
      }
      await uni.showToast({ title: '支付成功', icon: 'success', duration: 2000 })
      // 页面跳转
      await uni.redirectTo({ url: `/pagesOrder/payment/payment?id=${query.chId}` })
    }
  }, 3000)
})

// 倒计时结束事件
const orderStatus = ref('未支付')
const onTimeup = () => {
  console.log('倒计时结束，清除定时器')

  // 清除定时器
  if (timer) {
    clearInterval(timer)
    timer = null
  }

  // 修改订单状态为已取消
  orderStatus.value = '支付超时'
  uni.showToast({
    title: '支付超时',
    duration: 2000,
  })

  setTimeout(async () => {
    // 页面跳转或刷新
    await uni.redirectTo({ url: `/pagesOrder/details/details?id=${query.chId}&orderState=${0}` })
  }, 2000)
}
</script>

<template>
  <view class='page'>
    <view class='tips'>
      <!-- 应付金额 -->
      <view class='money'>应付金额: ¥ {{ urCode?.price }}</view>
      <view class='time'>
        <text>支付剩余</text>
        <uni-countdown
          :second="30"
          color="#000"
          splitor-color="#000"
          :show-day="false"
          :show-colon="false"
          @timeup="onTimeup"
        />
      </view>
    </view>
    <view class='qrcode'>
      <HosUqrcode
        canvas-id="qrcode"
        :value="urCode?.codeUrl"
        :options="{ margin: 10 }"
      ></HosUqrcode>
    </view>
  </view>
</template>

<style scoped lang='scss'>
.page {
  background-color: #00bb99;
  height: 100vh;
  text-align: center;

  .tips {
    padding: 50rpx 0;

    .time {
      margin: 20rpx 0;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .qrcode {
    width: 100%;
    text-align: center;
    margin-left: 25%;
  }
}
</style>
